package com.webs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static  String WEB_ROOT = "C:\\test";
	
	public Processor(){		}
	
	public Processor(Socket socket){
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void run(){
		String fileName = parse(in);
		sendFile(fileName);
	}

	
	//获取浏览器请求的文件名称
	private String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");//将请求信息按空格拆分
			
			if(content.length!=3){//判断请求的信息头不是3位长度,返回错误信息
				sendErrorMessage(400,"请求错误...");
				return null;
			}
			System.out.println("code:"+content[0]+",fileName"+content[1]+",http version:"+content[2]);
			fileName = content[1];//获取请求的文件名称
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	//向页面输出错误信息
	private void sendErrorMessage(int errorCode, String errorMessage) {
		//向页面返回信息
		out.println("HTTP/1.0 "+errorCode+" "+errorMessage);//返回信息头合格
		out.println("content-type:text/html");//返回文件格式
		out.println();//留空表示返回信息头结束
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("ErrorCode:"+errorCode+",Message:"+errorMessage);
		out.println("</body>");
		out.println("</html>");
		out.flush();//刷新缓存
		out.close();//关闭输出流
		try {
			in.close();//关闭输入流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//根据浏览器请求的文件名称,在服务器上指点目录下查找文件,找不到返回错误信息,找到文件就将文件返回给浏览器
	private void sendFile(String fileName) {
		File file = new File(Processor.WEB_ROOT+fileName);
		if(!file.exists()){
			sendErrorMessage(404,"文件不存在");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
